<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="3" :xs="24">
        <Tree :name="this.name" @projectSelect="isDevice" @deviceSelect="isDevice" style="margin-left: 20px;">
        </Tree>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="数据状态" prop="status">
            <el-select v-model="queryParams.flag" placeholder="请选择" clearable style="width: 240px" @change="handleQuery">
              <el-option v-for="dict in dict.type.alarm_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="查询范围">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              v-hasPermi="['system:user:import']">导入</el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange"
          @sort-change="sortChange">
          <el-table-column label="设备ID" width="120" align="center" fixed prop="deviceId" />
          <el-table-column label="设备名称"  align="center" fixed  prop="deviceName" />
          <el-table-column sortable label="报警类型" width="120" align="center" prop="flag">
            <template slot-scope="scope">
              <el-tag :type="scope.row.flag == '正常' ? 'success' : 'danger'"> {{ scope.row.flag }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable label="PM2.5"  align="center" key="pmTwoFive" prop="pmTwoFive"
            v-if="dusts[10].visible" />
          <el-table-column sortable label="PM10" align="center" key="pmTen" prop="pmTen"
            v-if="dusts[1].visible" :show-overflow-tooltip="true" />
          <!-- <el-table-column sortable label="噪声" align="center" width="120" key="zaosheng" prop="zaosheng"
            v-if="dusts[2].visible" :show-overflow-tooltip="true" />
          <el-table-column sortable label="温度" align="center" key="wendu" width="120" prop="wendu" v-if="dusts[3].visible"
            :show-overflow-tooltip="true" />
          <el-table-column sortable label="湿度" align="center" key="shidu" prop="shidu" width="120"
            v-if="dusts[4].visible" />
          <el-table-column sortable label="风力" align="center" key="fengli" prop="fengli" width="120"
            v-if="dusts[5].visible" />
          <el-table-column sortable label="风速" align="center" prop="fengsu" v-if="dusts[6].visible" width="120" />
          <el-table-column sortable label="风向(8方位)" align="center" prop="fengxiangDangWei" v-if="dusts[7].visible"
            width="160" />
          <el-table-column sortable label="风向" width="120" align="center" prop="fengxiang" v-if="dusts[8].visible" />

          <el-table-column sortable label="大气压" width="120" align="center" prop="daqiya" v-if="dusts[9].visible" />
          <el-table-column sortable label="光照"  width="120"  align="center" prop="guangzhao"  />
          <el-table-column sortable label="一氧化碳"  width="120" align="center" prop="yiyanghuantan"  /> -->

          <el-table-column sortable="custom" label="记录时间" width="160" align="center" prop="createTime">
            <template slot-scope="scope">
              {{ scope.row.createTime | formatDate }}
            </template>

          </el-table-column>


        </el-table>


        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

  </div>
</template>

<script>
import Tree from "@/components/Tree/Tree";
import { listUser } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect, NewdeptTreeSelect, listDevice } from "../../../api/system/device"
import moment from 'moment';
export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'alarm_flag'],
  components: { Treeselect, Tree },
  data() {
    return {
      name: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      props: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: undefined,
        beginTime: undefined,
        endTime: undefined,
        deviceId: undefined,
        status: undefined,
        flag: undefined,
        deptId: undefined
      },
      // 列信息
      dusts: [
        { key: 0, label: `设备名称`, visible: true, url: `` },
        { key: 1, label: `PM10`, visible: true, url: `` },
        { key: 2, label: `噪声`, visible: true, url: `` },
        { key: 3, label: `温度`, visible: true, url: `` },
        { key: 4, label: `湿度`, visible: true, url: `` },
        { key: 5, label: `风力`, visible: true, url: `` },
        { key: 6, label: `风速`, visible: true, url: `` },
        { key: 7, label: `风向(8方位)`, visible: true, url: `` },
        { key: 8, label: `风向`, visible: true, url: `` },
        { key: 9, label: `大气压`, visible: true, url: `` },
        { key: 10, label: `PM2.5`, visible: true, url: `` }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      //Tree加载样式
      loadingNodeId: null

    };
  },
  filters: {
    formatDate(dateString) {
      return moment(dateString).format("YYYY-MM-DD HH:mm:ss");
    }
  }
  ,
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);

    }
  },
  created() {
    this.name = this.$route.name
    this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    isDevice(e) {
      if (e.devId) {
        this.queryParams.deviceId = e.id
        this.queryParams.deptId = ''
      }
      else {
        this.queryParams.deviceId = ''
        this.queryParams.deptId = e.id
      }
      console.log(this.queryParams, '历史数据');
      this.handleQuery()
    },
    // 懒加载树加载数据
    loadNode(node, resolve) {
      if (node.level > 0) {
        if (!node.data.children) {
          this.$set(node.data, 'children', []);
          listDevice({ status: 3, deptId: node.data.id }).then(res => {
            const newNode = res.rows.map(item => ({
              id: item.deviceId,
              label: item.deviceName
            }))
            node.data.children.push(...newNode)
          })
        }
        return resolve(node.data.children);
      }
      setTimeout(() => {
        const data = this.deptOptions
        resolve(data);
      }, 500);
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    treeNodeClick(data, node) {
      this.queryParams.deptId = ''
      this.queryParams.deviceId = ''
      // 根据当前节点层级判断
      if (node.level > 1) {
        if (data.children.length > 0) {
          this.queryParams.deptId = node.data.id
          this.queryParams.deviceId = ''
        } else {
          this.queryParams.deptId = ''
          this.queryParams.deviceId = node.data.id
        }
      }
      this.handleQuery();
    },
    //Tree加载样式
    renderContent(h, { node, data }) {
      let label = h('span', node.label);
      // 如果当前节点正在加载数据，则显示加载图标
      if (this.loadingNodeId === data.id) {
        let loadingIcon = h('i', { class: 'el-icon-loading' });
        return h('span', [loadingIcon, label]);
      }
      // 否则只显示标签
      return label;
    },

    // 排序
    sortChange({ prop, order }) {
      this.userList.sort(this.compare(prop, order));
    },

    /**
       * 排序比较
       * @param {string} propertyName 排序的属性名
       * @param {string} sort ascending(升序)/descending(降序)
       * @return {function}
       */
    compare(propertyName, sort) {
      // 判断是否为数字
      function isNumberV(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
          return true;
        } else {
          return false;
        }
      }

      return function (obj1, obj2) {
        let value1 = obj1[propertyName];
        let value2 = obj2[propertyName];
        // 数字类型的比较
        if (isNumberV(value1) || isNumberV(value2)) {
          if (sort === "ascending") {
            return value1 - value2;
          } else {
            return value2 - value1;
          }
        }
        // 布尔值的比较：利用减法-转化true 和 false
        // true => 1   false ⇒ 0
        // true-false => 1  false-true => -1
        // 下面方法是按照先false后true的顺序排序，如果想先true后false，调整value1-value2 和  value2 - value1的顺序即可
        else if (_.isBoolean(value1) && _.isBoolean(value2)) {
          if (sort === "ascending") {
            return value1 - value2;
          } else {
            return value2 - value1;
          }
        }
        // 字符比较使用localeCompare()
        else {
          const res = value1.localeCompare(value2, "zh");
          return sort === "ascending" ? res : -res;
        }
      };
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        console.log('历史数据', response);
        this.userList = response.rows;
        console.log(this.userList)
        this.userList.forEach(item => {
          if (item.flag == 0) {
            item.flag = '正常'
          } else {
            item.flag = '报警'
          }
        })
        this.total = response.total;

        this.loading = false;
      }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      NewdeptTreeSelect().then(response => {

        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },


    // 节点单击事件
    async handleNodeClick(data) {
      // //只能单选时间
      // const { checked, indeterminate } = this.$refs.tree.getNode(data.id);
      // if (checked) {
      //   //如果是true说明点击其他节点时有其他复选框是勾选状态取消勾选不能发送请求
      //   console.log("取消选中")
      //   this.$refs.tree.setChecked(data.id, false);
      // } else {
      //   // 先将所有节点设置为非选中状态，再将当前节点设置为选中状态发送请求
      //   this.$refs.tree.setCheckedNodes([]);
      //   this.$refs.tree.setChecked(data.id, true);
      //   //在这里清空参数是因为如果我只想点击节点去查看数据的话，如果此时搜索框里有时间就会带着数据区查询，会找不到结果，所以点击节点的时候要先清空搜索框里的数据

      this.loadingNodeId = data.id;
      try {
        const DAta = await listDevice({ status: 3, deptId: data.id })
        this.loadingNodeId = null;

        if (!data.children) {
          this.$set(data, 'children', [])
        }
        if (DAta.rows.length > 0) {
          const newNode = DAta.rows.map(item => ({
            id: item.deviceId,
            label: item.deviceName
          }))
          data.children.push(...newNode)
          this.$refs.tree.updateKeyChildren(data.id, data.children)
        }
        this.rest()

        if (data.children.length > 0) {
          //在这里通过判断是否有children来判断是项目还是设备
          this.queryParams.deviceId = ''
          this.queryParams.deptId = data.id
        } else {
          this.queryParams.deptId = ''
          this.queryParams.deviceId = data.id
        }
        this.handleQuery();

      } catch (err) {
        this.loadingNodeId = null;
      }

    },
    isObject(obj) {
      return obj !== null && typeof obj === 'object'
    },
    // 取消按钮

    /** 搜索按钮操作 */
    handleQuery() {
      // this.dict.label.sys_normal_disable
      if (this.queryParams.deviceName) {
        //搜索设备名字应该就不是点击节点触发的搜索了，所以把节点的参数都为空，树节点是通过ID查
        this.queryParams.deviceId = undefined
        this.queryParams.deptId = undefined
        // this.$refs.tree.setCurrentKey(null); // 将当前选中的节点设置为null
      } else { }
      if (!this.dateRange || this.dateRange.length === 0) {
        this.dateRange = []
      } else {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      }
      console.log(this.queryParams)
      this.getList()

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.rest()
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.queryParams.deviceId = undefined
      this.$refs.tree.setCurrentKey(null);
      this.$refs.tree.setCheckedNodes([]);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    rest() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        deviceName: undefined,
        beginTime: undefined,
        endTime: undefined,
        deviceId: undefined,
        status: undefined,
        deptId: undefined
      }
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },


  }
};
</script>
